local S = minetest.get_translator("map_making_toolkit")


local function save_cmd_func(name, param)
	--parse arguments and get the corners of the box with
	--minimal/maximal coordinates
	

	local worked, pos1, offset = map_making_toolkit.parse_args(param)
	if not worked or offset.x == 0 or offset.y == 0 or offset.z == 0
	then
		return true, S("Invalid coordinates or offset")
	end
	
	
	minpos = {}
	
	for k, v in pairs(pos1)
	do
		minpos[k] = math.min(v, v + (offset[k] - 1) * 16)
		offset[k] = math.abs(offset[k])
	end
	
	
	
	local mapid = math.random()
	local path = minetest.get_worldpath()
	path = path .. "/schematics/map" .. mapid .. "/"
	minetest.mkdir(path)
	
	
	
	
	for i = 0, offset.x - 1
	do
		local ix = minpos.x + i * 16
		
		for ii = 0, offset.y - 1
		do
			local iy = minpos.y + ii * 16
			
			for iii = 0, offset.z - 1
			do
				local iz = minpos.z + iii * 16
				
				
				local pos1 = vector.new(ix, iy, iz)
				local pos2 = vector.add(pos1, vector.new(15, 15, 15))
				local filename = path..i.."_"..ii.."_"..iii..".mts"
				
				minetest.create_schematic(pos1, pos2, nil, filename)
			end
		end
	end
	return true, S("Saved schematic files to:\n@1", path)
end

minetest.register_chatcommand("savemap",
	{
		params = S("<x> <y> <z> <offset x> <offset y> <offset z>"),
		privs = {server = true},
		description = S("Saves a map as a bunch of 16x16x16 schematics " ..
			"in the world directory.\n" ..
			"Offset is in map blocks."),
		func = save_cmd_func,
	})
